import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class FlowLayoutTest extends JFrame{
    private boolean openfile = false;
    private File file;
    public JSlider slider;
    public int mychoicevert;
    private String mychoice = "Алгоритм Прима";
    private GraphTS gts;
    private Dijkstra D;
    private mxGraph graph;
    private mxGraph twograph;
    private GraphPrima gpr;
    public ReadFileClass openf;
    public  String[] items = {"Алгоритм Прима","Алгоритм Дейкстры","Топологическая сортировка"};
    public FlowLayoutTest(){
        super("Graphs Algorithms Visualization");
        setVisible(true);
        graph = new mxGraph();
        twograph = new mxGraph();
        final Object parent = graph.getDefaultParent();
        final Object parent2 = twograph.getDefaultParent();
        D = new Dijkstra();
        gts = new GraphTS();
        gpr = new GraphPrima();
        //======================================================================
        Toolkit.getDefaultToolkit().setDynamicLayout(true);
        final JPanel content = new JPanel();
        content.setLayout(new BoxLayout(content,BoxLayout.Y_AXIS));
        final JPanel content2 = new JPanel();
        final JPanel content3 = new JPanel();
        content3.setLayout(new BoxLayout(content3,BoxLayout.Y_AXIS));
        JLabel lblAlgorithms = new JLabel("Algorithms:");
        final JLabel vertsx = new JLabel("Начальная вершина:");
        final mxGraphComponent graphComponent = new mxGraphComponent(graph);
        mxGraphComponent graphComponenttwo = new mxGraphComponent(twograph);
        //======================================================================
        final JComboBox cbxAlignments = new JComboBox(items);
        final JComboBox vert = new JComboBox();
        JButton btn = new JButton("Выбрать Файл");
        final JButton start = new JButton("Начать");
        //======================================================================
        graph.setCellsMovable(false);
        graph.setCellsEditable(false);
        graph.setCellsResizable(false);
        graph.setCellsSelectable(false);
        graph.setConnectableEdges(false);
        graph.setResetEdgesOnMove(false);
        graph.setResetEdgesOnResize(false);
        graph.setKeepEdgesInBackground(false);
        graph.setKeepEdgesInForeground(false);
        graph.setEdgeLabelsMovable(false);
        graph.setResetEdgesOnConnect(false);
        graph.setResetViewOnRootChange(false);
        graph.setAllowDanglingEdges(false);
        graph.setLabelsClipped(false);
        twograph.setCellsMovable(false);
        twograph.setCellsEditable(false);
        twograph.setCellsResizable(false);
        twograph.setCellsSelectable(false);
        twograph.setConnectableEdges(false);
        twograph.setResetEdgesOnMove(false);
        twograph.setResetEdgesOnResize(false);
        twograph.setKeepEdgesInBackground(false);
        twograph.setKeepEdgesInForeground(false);
        twograph.setEdgeLabelsMovable(false);
        twograph.setResetEdgesOnConnect(false);
        twograph.setResetViewOnRootChange(false);
        twograph.setAllowDanglingEdges(false);
        twograph.setLabelsClipped(false);
        //======================================================================
        cbxAlignments.setSelectedIndex(0);
        cbxAlignments.setBorder(BorderFactory.createEmptyBorder(0,5,0,5));       
        lblAlgorithms.setVerticalAlignment(JLabel.CENTER);
        lblAlgorithms.setHorizontalAlignment(JLabel.LEFT);
        //======================================================================
        slider = new JSlider(JSlider.HORIZONTAL, 1, 1500, 600);
        slider.setMajorTickSpacing(300);
        slider.setMinorTickSpacing(100);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setSnapToTicks(true);
        //======================================================================
        content.add(graphComponent);
        content3.add(graphComponenttwo);
        content2.add(lblAlgorithms);
        content2.add(cbxAlignments);
        content2.add(btn);
        content2.add(start);
        content2.add(vertsx);
        content2.add(vert);
        content.setPreferredSize(new Dimension(700, 500));
        content3.setPreferredSize(new Dimension(250, 450));
        content2.setPreferredSize(new Dimension(700, 80));
        vert.setEnabled(false);    
        //======================================================================
        getContentPane().add(content, BorderLayout.CENTER);
        getContentPane().add(content2, BorderLayout.SOUTH);
        getContentPane().add(content3, BorderLayout.EAST);
        //======================================================================
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        //======================================================================
        btn.addActionListener(new ActionListener() {
                        @Override
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileopen = new JFileChooser();				
				int ret = fileopen.showDialog(null, "Открыть файл");				
				if (ret == JFileChooser.APPROVE_OPTION) {
					file = fileopen.getSelectedFile();
                                        openf = new ReadFileClass();
                                    try {
                                        openfile = openf.ReadFile(file.getName());
                                        if(openfile){
                                        Mychoice(openf.GetMaxVertex(),vert);
                                        }
                                        mychoicevert = 1;
                                    } catch (IOException ex) {
                                        Logger.getLogger(FlowLayoutTest.class.getName()).log(Level.SEVERE, null, ex);
                                    }
				}
			}
		});
        //======================================================================
        start.addActionListener(new ActionListener() {
                        @Override
			public void actionPerformed(ActionEvent e) {
                            if(file!=null){
                                if(openfile){
				if(mychoice == null ? items[0] == null : mychoice.equals(items[0])){
                                    new Thread(new Runnable(){
                                                @Override
                                                public void run(){
                                                graph.removeCells(graph.getChildCells(graph.getDefaultParent(), true, true));
                                                twograph.removeCells(twograph.getChildCells(twograph.getDefaultParent(), true, true));
                                                    try {
                                                        start.setEnabled(false);
                                                        gpr.Init(openf, graph, parent);
                                                        gpr.SortPrima(openf, graph, parent,twograph,parent2,mychoicevert,slider);
                                                        start.setEnabled(true);
                                                    } catch (InterruptedException ex) {
                                                        Logger.getLogger(FlowLayoutTest.class.getName()).log(Level.SEVERE, null, ex);
                                                    }
                                     
                                    }
                                    }).start();
                                }
                                if(mychoice == null ? items[1] == null : mychoice.equals(items[1])){
                                    new Thread(new Runnable(){
                                                @Override
                                                public void run(){
                                                graph.removeCells(graph.getChildCells(graph.getDefaultParent(), true, true));
                                                twograph.removeCells(twograph.getChildCells(twograph.getDefaultParent(), true, true));
                                                    try {
                                                       start.setEnabled(false);
                                                       D.Init(openf, graph, parent,twograph,parent2);
                                                       D.Dijkstra(openf, graph, parent, twograph, parent2,mychoicevert,slider);
                                                       start.setEnabled(true);
                                                    } catch (InterruptedException ex) {
                                                        Logger.getLogger(FlowLayoutTest.class.getName()).log(Level.SEVERE, null, ex);
                                                    }
                                     }
                                    }).start();
                                }
                                if(mychoice == null ? items[2] == null : mychoice.equals(items[2])){
                                    new Thread(new Runnable(){
                                                @Override
                                                public void run(){
                                    try {
                                        graph.removeCells(graph.getChildCells(graph.getDefaultParent(), true, true));
                                        twograph.removeCells(twograph.getChildCells(twograph.getDefaultParent(), true, true));
                                        start.setEnabled(false);
                                        gts.Init(openf, graph, parent);
                                        gts.Sort(openf,graph,parent,twograph,parent2,slider);
                                        start.setEnabled(true);
                                    } catch (InterruptedException ex) {
                                        Logger.getLogger(FlowLayoutTest.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                     }
                                    }).start();                                      
                                }                               
			}
                        }
                        }
		});
        //======================================================================
         vert.addActionListener(new ActionListener() {
                        @Override
			public void actionPerformed(ActionEvent e) {
				JComboBox box = (JComboBox)e.getSource();
                                if(box.getItemCount()>0){
		                mychoicevert = (Integer)box.getSelectedItem();
                                }
			}
		});
        //======================================================================
        cbxAlignments.addActionListener(new ActionListener() {
                        @Override
			public void actionPerformed(ActionEvent e) {                          
				JComboBox box = (JComboBox)e.getSource();
		                mychoice = (String)box.getSelectedItem();
                                if((mychoice == null ? items[0] == null : mychoice.equals(items[0]))||(mychoice == items[1])){
                                    if(vert.getItemCount()>0){
                                        vert.setEnabled(true);
                                    } else { vert.setEnabled(false);}
                                } else {
                                    vert.setEnabled(false);
                                }
                        }
            });
        addMouseWheelListener(new MouseAdapter() {
            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                //super.mouseWheelMoved(e);    // Прокрутка "колёсиком" мыши
                if (e.getWheelRotation() < 0)
		{
			graphComponent.zoomIn();  
		}else{
			graphComponent.zoomOut();    
		}
            }
        });
        JButton btZoomToFit = new JButton("R");
        btZoomToFit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                double newScale = 1;
                Dimension graphSize = graphComponent.getGraphControl().getSize();
                Dimension viewPortSize = graphComponent.getViewport().getSize();
                int gw = (int) graphSize.getWidth();
                int gh = (int) graphSize.getHeight();
                if (gw > 0 && gh > 0) {
                    int w = (int) viewPortSize.getWidth();
                    int h = (int) viewPortSize.getHeight();
                    newScale = Math.min((double) w / gw, (double) h / gh);
                }
                graphComponent.zoom(newScale);
            }
        });
        content2.add(btZoomToFit);
        content2.add(slider);
    }
    public void Mychoice(int verttmax,JComboBox vert){
        vert.setEnabled(false);
        vert.removeAllItems();
        for(int i=0;i<verttmax;i++){
               vert.addItem(i+1);
           }
        if(mychoice == null ? items[2] != null : !mychoice.equals(items[2]))
        vert.setEnabled(true);
    }
}